package tables

import (
	"encoding/json"
	"fmt"
	"peilian-api/app/global/variable"
	"time"

	"gorm.io/gorm"
)

const (
	RolesLevel0 = 0 // 普通学生 默认无后台权限
	RolesLevel1 = 1 // 超级账户角色等级
	RolesLevel2 = 2 // 学校管理员角色等级
	RolesLevel3 = 3 // 学院管理员角色等级
	RolesLevel4 = 4 // 专业管理员角色等级

	IsCustom    = true
	IsNotCustom = false
)

type Roles struct {
	gorm.Model
	UserId     uint         `gorm:"default:0;comment:添加角的用户id"`
	RoleName   string       `gorm:"type:varchar(128);default:'';comment:角色名称"`
	Powers     string       `gorm:"type:varchar(256);default:'';comment:页面权限id"`
	Level      int          `gorm:"type:tinyint(3);default:0;comment:权限等级"`
	Describe   string       `gorm:"type:varchar(256);comment:描述"`
	BelongToId uint         `gorm:"default:0;comment:隶属账户学校|学院|专业id"`
	IsCustom   bool         `gorm:"default:false;comment:是否自定义管理员true|false"`
	Member     []CommonConf `gorm:"foreignKey:id;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
}

func (r *Roles) TableName() string {
	return "roles"
}

func (r *Roles) SaveRoles(role Roles) error {
	fmt.Println(role)
	if d := variable.DB.MySQL.Save(&role); d.Error != nil {
		return d.Error
	}
	return nil
}

func (r *Roles) GetRolesByWhere(whereMap map[string]interface{}, whereStr string) ([]Roles, error) {
	var roles []Roles
	if len(whereMap) == 0 {
		if d := variable.DB.MySQL.Model(Roles{}).Where(whereStr).Find(&roles); d.Error != nil {
			return roles, d.Error
		}
	} else if len(whereStr) == 0 {
		if d := variable.DB.MySQL.Model(Roles{}).Where(whereMap).Find(&roles); d.Error != nil {
			return roles, d.Error
		}
	} else {
		if d := variable.DB.MySQL.Model(Roles{}).Where(whereMap).Where(whereStr).Find(&roles); d.Error != nil {
			return roles, d.Error
		}
	}

	return roles, nil
}

// 含有公共权限
func (r *Roles) GetRolesDetailByWhere(whereStr string) ([]Roles, error) {
	var roles []Roles
	if d := variable.DB.MySQL.Model(&Roles{}).Where(whereStr).FindInBatches(&roles, 10, func(tx *gorm.DB, batch int) error {
		if batch == 0 {
			return fmt.Errorf("数据库查询异常")
		}
		for i := 0; i < len(roles); i++ {
			var arr []int
			json.Unmarshal([]byte(roles[i].Powers), &arr)
			if d := variable.DB.MySQL.Model(&CommonConf{}).Where("id in (?) and conf_key = ?", arr, ConfKeyRoleUri).Order("type desc").Find(&roles[i].Member); d.Error != nil {
				return d.Error
			}
		}
		return nil
	}); d.Error != nil {
		return roles, fmt.Errorf("数据查询异常")
	}
	return roles, nil
}

// 除公共权限
func (r *Roles) GetRolesDetailNoPubByWhere(whereStr string) (Roles, error) {
	var roles Roles
	if d := variable.DB.MySQL.Model(&Roles{}).Where(whereStr).FindInBatches(&roles, 10, func(tx *gorm.DB, batch int) error {
		if batch == 0 {
			return fmt.Errorf("数据库查询异常")
		}
		var arr []int
		json.Unmarshal([]byte(roles.Powers), &arr)
		if d := variable.DB.MySQL.Model(&CommonConf{}).Where("id in (?) and conf_key = ?", arr, ConfKeyRoleUri).Order("type desc").Find(&roles.Member); d.Error != nil {
			return d.Error
		}

		return nil
	}); d.Error != nil {
		return roles, fmt.Errorf("数据查询异常")
	}
	return roles, nil
}

func (r *Roles) GetRolesPaging(whereMap map[string]interface{}, order string, page, pageSize int) (int64, []Roles, error) {
	var roles []Roles
	var count int64
	if d := variable.DB.MySQL.Model(Roles{}).Where(whereMap).Offset((page - 1) * pageSize).Limit(pageSize).Order(order).Find(&roles).Offset(-1).Limit(-1).Count(&count); d.Error != nil {
		return count, roles, d.Error
	}
	return count, roles, nil
}

// 根据用户id逻辑删除角色信息
func (r *Roles) DeleteRolesById(id int) (int64, error) {
	var role Roles
	d := variable.DB.MySQL.Where("id = ?", id).Find(&role)
	if d.RowsAffected == 0 {
		return d.RowsAffected, fmt.Errorf("数据不存在，无法删除")
	}
	role.DeletedAt = gorm.DeletedAt{time.Now(), true}
	d = variable.DB.MySQL.Where("id = ?", id).Updates(&role).Limit(1)
	return d.RowsAffected, d.Error
}

// 根据用户id更新数据
func (r *Roles) UpdateRolesById(updates map[string]interface{}, id int) error {
	if d := variable.DB.MySQL.Model(r).Where("id = ?", id).Updates(updates).Limit(1); d.Error != nil {
		return d.Error
	}
	return nil
}
